package com.liangge.essaysite.tools;

import java.util.Date;
import java.util.Iterator;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.liangge.essaysite.bean.SiteProperty;
import com.liangge.essaysite.service.SitePropertyService;
import com.liangge.essaysite.util.AgentKeys;
import com.liangge.essaysite.util.CfgUtils;

public class DBTools {
	/**
	 * 根据common.properties中的配置项初始化到siteproperties表
	 * @author liangge
	 */
	public static void insertPropertiesToDB() throws Exception{
		ApplicationContext context = new ClassPathXmlApplicationContext("spring-common.xml");
		SitePropertyService sitePropertyService = (SitePropertyService)context.getBean("sitePropertyService");
		
		Configuration config = CfgUtils.getCommonCfg();
		for(Iterator<String> it = config.getKeys(AgentKeys.P_PREFIX);it.hasNext();){
			String configKey = it.next();
			//获取propertyName
			String propertyName = StringUtils.substringBetween(configKey, AgentKeys.KEYS_SEPARATE, AgentKeys.KEYS_SEPARATE);
			//获取propertyId
			String propertyId = StringUtils.substringAfterLast(configKey, AgentKeys.KEYS_SEPARATE);
			//获取propertyValue
			String propertyValue = config.getString(configKey);
			
			SiteProperty siteProperty = new SiteProperty();
			siteProperty.setPropertyId(Integer.valueOf(propertyId));
			siteProperty.setPropertyName(propertyName);
			siteProperty.setPropertyValue(propertyValue);
			siteProperty.setPropertyRemark(propertyName);
			siteProperty.setCreateTime(new Date());
			siteProperty.setUpdateTime(new Date());
			
			int insert = sitePropertyService.insertSiteProperty(siteProperty);
			if(insert == 1){
				System.out.println(configKey+" insert success!");
			}else{
				System.out.println(configKey+" insert failure!");
			}
		}
	}
	
	public static void main(String[] args) throws Exception{
		insertPropertiesToDB();
	}
}
